#include "rdb_lib.h"
#include "Python.h"

#include "signal.h"
#include "DumpHelp.h"
#include "common.h"
#include "ReadScript.h"
#include "ScriptStruct.h"
#include <QCoreApplication>
#include <QDebug>
#include <QDir>

/************************************************************************
**读取脚本文件“*.cal”
**解析
**运行
************************************************************************/
void ReadParseExeScript(ScriptStruct *parser, const QString &path)
{
    QDir dir(path);
    QFileInfoList fileNameList = dir.entryInfoList(QStringList("*.cal"));

    foreach(QFileInfo file, fileNameList)
    {
        qDebug()<<file.absoluteFilePath();
        parser->ParseSource(file.absoluteFilePath());
    }

    QFileInfoList dirNameList = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
    foreach(QFileInfo dirName, dirNameList)
    {
        qDebug()<<"dir "<<dirName.absoluteFilePath();
        ReadParseExeScript(parser, dirName.absoluteFilePath());
    }

}

void ReadParseExeScript()
{
    ScriptStruct sc;

    char path[128];
    get_system_dir(path, 128);

    QString filePath = QString(path) + QDir::separator() + "script" + QDir::separator() + "CalScript";

    ReadParseExeScript(&sc, filePath);
}

int main(int argc, char **argv)
{
    INSTALL_DUMPHANDLER
    SETLOGFILE("PyCalEngine");

    QCoreApplication app(argc, argv);

    ReleasePromanSem();

    Py_Initialize();
    if (!Py_IsInitialized())
    {
        TRACE_ERROR("Python 运行环境没有初始化！");
        exit(1);
    }

    if(InitApp(SCADA) < 0)
    {
        TRACE_ERROR("init App scada failed\n");
        exit(1);
    }

    if(dbg::instance()->init(argc, argv) == false) 
    {
        Py_Finalize();
        ShutDownApp(SCADA);
        exit(1);
    }
    if(dbg::instance()->Debug())//debug
    {
        dbg::instance()->test();
    }
    else
    {
        if ( ProcessCounter("PyCalEngine").counter() > 1) //一个进程
        {
            ReleasePromanSem();
            TRACE_WARN("process has existed.\n");
            exit(1);
        }

        ReadParseExeScript();
    }
        
    int ret = app.exec();
    Py_Finalize();
    ShutDownApp(SCADA);
    return ret;
}